<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/8/23
 * Time: 11:12
 */

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\services\customer\Account;
use common\components\services\msg\MsgBehavior;
use common\models\datas\CardAttr;
use common\models\datas\CardSend;
use common\models\datas\Customer;
use common\models\datas\CustomerRegisterRelation;
use common\models\datas\Setting;
use common\models\datas\Student;
use common\models\datas\Apply;
use zhtfrontend\models\datas\Mechanic;
use yii\bootstrap\ActiveForm;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\data\Pagination;


class ScholarshipappController extends \zhtfrontend\components\bases\BaseController
{
    public function actions()
    {
        return [
/**Apply的状态更改自动触发发送，所以我就先注释啦
            'sendsmsmessage' => [//发送成功验证码
                'class' => 'doumiaoduo\telecaptcha\SendapplyAction',
                'behaviorsData' => [
                    [
                        'class' => MsgBehavior::className(),
                    ]
                ],
            ],
            'sendsmsmessagefail' => [//发送成功验证码
                'class' => 'doumiaoduo\telecaptcha\SendapplyfailAction',
                'behaviorsData' => [
                    [
                        'class' => MsgBehavior::className(),
                    ]
                ],
            ],*/
        ];
    }

    public function actionIndex()
    {
        $param['searchData'] = \Yii::$app->request->get();
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
        $data = Apply::find()->where(['site_id' => Fun::getSiteId()])->orderBy('id DESC');
        if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'mechanic') {
            $mids = Fun::getMechanicIds();
            if (!empty($param['searchData']) && $param['searchData']['telephone']) {
                $search_data = $param['searchData'];
                $data->andWhere(['telephone' => $search_data['telephone']]);
            } else {
                $data->andWhere(['mechanic_id' => $mids]);
            }
        } else {
            if (!empty($param['searchData'])) {
                $search_data = $param['searchData'];
                if (!empty($search_data['telephone'])) {
                    $data->andWhere(['telephone' => $search_data['telephone']]);
                }
                if (isset($search_data['status']) && $search_data['status'] != null) {
                    $data->andWhere(['status' => $search_data['status']]);
                }

            }
        }
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $list = Fun::asArray($model, ['datebirth', 'cate_name', 'mechanic_name', 'operate']);

        return $this->render('index', ['data' => $list, 'pages' => $pages]);
    }

    public function actionHandle()
    {
        $this->layout = '@app/views/layouts/iframe.php';

        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Apply::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->scenario = 'handle';
        if ($model->status == 0) {
            $model->status = 1;
        }
        $model->dues_proportion = 0;

        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $model->updated_at = time();
            $new_remarks = $model->new_remark . "\n" . \Yii::$app->formatter->asDatetime(time());
            $str = '';
            if (!empty($model->remarks)) {
                $str = $model->remarks . "\n";
            }
            $model->remarks = $str . $new_remarks;
            if ($model->status == 2) {
                $cardModel = CardAttr::find()->where(['sendtype' => 2, 'salesman_id' => 0, 'customer_id' => NULL, 'site_id' => $model->site_id])->orderBy('id ASC')->one();
                if ($cardModel == null) {
                    return $this->redirectMessage('处理失败，推荐卡不存在', Fun::url(['scholarshipapp/index']));
                }
                $model->card_attr_id = $cardModel->id;
                $model->v_code = $cardModel->v_code;
            }
            $model->operator_id = \Yii::$app->user->id;
            $model->operator = \Yii::$app->user->identity->name;
            if ($model->save(false)) {
                if ($model->status == 2) {
                    $customerModel = Customer::find()->where(['mobile' => $model->telephone])->one();
                    if ($customerModel == null) {
                        $customerModel = new Customer();
                        $customerModel->site_id = Fun::getSiteId();
                        $customerModel->name = $model->telephone;
                        $customerModel->mobile = $model->telephone;
                        $customerModel->created_at = time();
                        if ($customerModel->save(false)) {

                            $CustomerRegisterRelation = new CustomerRegisterRelation();
                            $CustomerRegisterRelation->site_id = Fun::getSiteId();
                            $CustomerRegisterRelation->customer_id = $customerModel->id;
                            $CustomerRegisterRelation->mode = 1;
                            $CustomerRegisterRelation->save(false);
                            //插入学生
                            $studentModel = new Student();
                            $studentModel->customer_id = $customerModel->id;
                            $studentModel->created_at = time();
                            $studentModel->name = $model->student_name;
                            $studentModel->nickname = $model->student_name;
                            $studentModel->age = $model->borth_year;
                            $studentModel->sex = 0;
                            $studentModel->site_id = Fun::getSiteId();
                            $studentModel->save(false);
                        }
                    }
                    //增加奖学金及插入奖学金记录
                    $scholarshipData = Setting::findOne(['key' => 'scholarship', 'branch_id' => 0]);
                    $scholarship_info = !empty($scholarshipData->value) ? unserialize($scholarshipData->value) : ['vip' => 2000];
                    $cardModel->customer_id = $customerModel->id;
                    $cardModel->cash = $scholarship_info['vip'];
                    $cardModel->status = 1;
//                        $cardModel->site_id = Fun::getSiteId();
                    $cardModel->active_time = time();
                    $cardModel->salesman_id = $customerModel->id;
                    $cardModel->issuser_id = $customerModel->id;
                    $cardModel->obtain_type = 2;
                    $cardModel->save(false);

                    $CardSendModel = new CardSend();
                    $CardSendModel->number = 1;
                    $CardSendModel->user_id = \Yii::$app->user->id;
                    $CardSendModel->salesman_id = $customerModel->id;
                    $CardSendModel->issuser_id = $customerModel->id;
                    $CardSendModel->send_type = 1;
                    $CardSendModel->batch_id = $cardModel->batch_id;
                    $CardSendModel->card_start = $cardModel->card_id;
                    $CardSendModel->card_end = $cardModel->card_id;
                    if (\Yii::$app->user->identity->role == 'mechanic') {
                        $CardSendModel->dues_proportion = 0;
                    } else {
                        $CardSendModel->dues_proportion = $model->dues_proportion;
                    }
                    $CardSendModel->site_id = Fun::getSiteId();
                    $CardSendModel->save(false);

                    \Yii::$app->runAction('scholarshipapp/sendsmsmessage', ['apply_id' => $id]);
                }
                if ($model->status == 3) {
                    \Yii::$app->runAction('scholarshipapp/sendsmsmessagefail', ['apply_id' => $id]);
                }
                return $this->redirectMessage('处理成功', Fun::url(['scholarshipapp/index']));
            } else {
                return $this->redirectMessage('处理失败', Fun::url(['scholarshipapp/index']));
            }
        }
        return $this->render('handle', ['model' => $model]);
    }

    public function actionView()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Apply::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }

        return $this->render('view', ['model' => $model]);
    }


}